package orch

import (
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/shells"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
	"os"
	"strings"
)

func promptRunModules(wrapper *config.Wrapper, plan FlowPlan) hcl.Diagnostics {
	if plan.NeedRunNumber() <= 1 {
		logrus.Debugf("no need to run modules, only %d module(s) need to be run", plan.NeedRunNumber())
		return nil
	}

	prompt := "\nThis command will run with the following modules.\n"
	for _, group := range plan {
		newLine := true
		for _, module := range group {
			if module.NeedRun {
				if newLine {
					prompt += "\n    "
				}
				prompt += color.HiGreenString("module.%s ", module.Name)
				newLine = false
			}
		}
	}
	prompt += "\n\nAre you sure you want to run these modules? "

	if err := shells.PromptUserForYesNo(wrapper.Config.NonInteractive, prompt, os.Stderr); err != nil {
		return errors.NewDiagnostics("Unconfirmed !", err.Error())
	}
	return nil
}

func RunAll(wrapper *config.Wrapper, args []string) hcl.Diagnostics {
	plan, diags := Validate(wrapper)
	if util.HasErrors(diags) {
		return diags
	}

	logrus.Infof("run-all args: %s", color.HiYellowString(strings.Join(args, " ")))

	if wrapper.RunInModuleName != "" {
		plan.MarkModuleRun(wrapper.RunInModuleName)
	} else if wrapper.IsRunInStackDir {
		plan.MarkRunAll()
	}

	if diags = promptRunModules(wrapper, plan); util.HasErrors(diags) {
		return diags
	}

	for _, group := range plan {
		for _, step := range group {
			if step.NeedRun {
				if _, diags = runModule(wrapper, step.Name, args); util.HasErrors(diags) {
					return diags
				}
			}
		}
	}
	return nil
}
